import Koa from 'koa';
import http from 'http';
import { Server } from 'socket.io';
import cors from '@koa/cors';
import { koaBody } from 'koa-body';
import serve from 'koa-static';
import path from 'path';
import { fileURLToPath } from 'url';
import { responseHandler } from './middlewares/response.js';
import userRouter from './routes/user.js';
import apiRouter from './routes/api.js';
import adminRouter from './routes/admin.js';
import serviceStaffRouter from './routes/serviceStaff.js';
import defaultAvatarRouter from './routes/defaultAvatar.js';
import uploadRouter from './routes/upload.js';
import socketHandler from './socket/index.js';
import dotenv from 'dotenv';
import { initDatabase } from './config/database.js';
import fs from 'fs';

// 获取当前文件的目录路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 根据环境加载配置
const env = process.env.NODE_ENV || 'development';
const envPath = path.resolve(__dirname, `../.env.${env}`);

console.log('Application Info:');
console.log('- Current working directory:', process.cwd());
console.log('- Application directory:', path.resolve(__dirname, '..'));
console.log('- Environment:', env);
console.log('- Env file path:', envPath);
console.log('- Env file exists:', fs.existsSync(envPath));

// 尝试加载环境变量
try {
  const result = dotenv.config({ path: envPath });
  
  if (result.error) {
    console.error('Error loading environment variables:', result.error.message);
  } else {
    console.log('Environment variables loaded successfully');
  }
} catch (error) {
  console.error('Failed to load environment variables:', error);
}

// 打印所有环境变量用于调试
console.log('\nEnvironment variables:');
console.log('- NODE_ENV:', process.env.NODE_ENV);
console.log('- JWT_SECRET:', process.env.JWT_SECRET);
console.log('- SERVER_URL:', process.env.SERVER_URL);
console.log('- SMTP_HOST:', process.env.SMTP_HOST);

if (!process.env.JWT_SECRET) {
  console.error('\nWARNING: JWT_SECRET is not defined in environment variables');
  console.error('Please make sure .env.${env} file exists and contains JWT_SECRET');
}

const app = new Koa();
const httpServer = http.createServer(app.callback());

// 创建 Socket.IO 服务器
const io = new Server(httpServer, {
  cors: {
    origin: "*", // 在生产环境中应该设置具体的域名
    methods: ["GET", "POST"]
  }
});

// 注册 socket 处理器
socketHandler(io);
console.log('Socket.IO server initialized');

// 错误处理中间件
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.status || 500;
    ctx.body = { error: err.message };
    ctx.app.emit('error', err, ctx);
  }
});

// 中间件
app.use(cors());

// 配置文件上传
app.use(koaBody({
  multipart: true,
  formidable: {
    maxFileSize: 5 * 1024 * 1024, // 5MB
    keepExtensions: true,
    uploadDir: path.join(process.cwd(), 'temp')
  }
}));

// 静态文件服务
app.use(serve(path.join(process.cwd(), 'public')));

// 添加统一响应处理中间件
app.use(responseHandler);

// 注册路由
app.use(userRouter.routes()).use(userRouter.allowedMethods());
app.use(apiRouter.routes()).use(apiRouter.allowedMethods());
app.use(adminRouter.routes()).use(adminRouter.allowedMethods());
app.use(serviceStaffRouter.routes()).use(serviceStaffRouter.allowedMethods());
app.use(defaultAvatarRouter.routes()).use(defaultAvatarRouter.allowedMethods());
app.use(uploadRouter.routes()).use(uploadRouter.allowedMethods());

// 错误处理
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx);
});

// 启动服务器
async function startServer() {
  try {
    // 初始化数据库
    await initDatabase();
    console.log('Database initialized successfully');

    const port = process.env.PORT || 9528;
    httpServer.listen(port, () => {
      console.log(`HTTP Server is running on port ${port}`);
      console.log(`Socket.IO Server is ready for connections`);
    });
  } catch (error) {
    console.error('Failed to start server:', error);
    process.exit(1);
  }
}

export default httpServer;

startServer();
